import { reactControl, BaseReactElementControl, CookieUtil } from "pao-aop-client";
import { addon } from "pao-aop";
import React from "react";
import { Form, Select, Input, Radio, Button, Row, Checkbox, } from "antd";
import TextArea from "antd/lib/input/TextArea";
import { AppServiceUtility } from "src/projects/app/appService";
import { User } from "src/business/models/user";
import { COOKIE_KEY_CURRENT_USER } from "src/business/mainForm/backstageManageMainForm";
import { FileUploadBtn } from "src/business/components/buss-components/file-operation-btn/file-upload-btn";
import { remote } from "src/projects/remote";
import { beforeUpload } from "src/projects/app/util-tool";
const { Option } = Select;
/**
 * 组件：初步评估表单状态
 */
export class PreliminaryAssessmentFormState {
    /** 模板集合 */
    template_list?: any[];
    /** 项目集合 */
    project_list?: any[];
    /** 项目评分 */
    score?: number;
    // 项目评分储存
    score_array: any[];
    /*申请表里的选项和值 */
    project?: any;
    // 模板是否改变了
    isTplchange?: boolean;
    // 是否需要护理等级字段
    NursingLevel?: any;
}

/**
 * 组件：初步评估表单
 * 初步评估表单
 */
export class PreliminaryAssessmentForm extends React.Component<PreliminaryAssessmentFormControl, PreliminaryAssessmentFormState> {
    constructor(props: any) {
        super(props);
        this.state = {
            template_list: [],
            project_list: [],
            score_array: [],
            isTplchange: false,
            NursingLevel: [],
        };
    }
    /** 选择模板选择框值改变 */
    template_change = (value: any) => {
        AppServiceUtility.assessment_template_service.get_assessment_template_list!({ template_type: '初步能力评估', id: value }, 1, 10)!
            .then((data: any) => {
                if (data.result) {
                    this.setState({
                        project_list: data.result,
                        score: 0,
                        isTplchange: true,
                    });
                }
            });
    }
    componentWillMount() {
        /** 获取评估模板那 */
        let condition = {};
        if (this.props['isNursingLevel']) { // 入住评估
            const nursing_level = ['自理', '介护1', '介护2', '介助1', '介助2', '个性化护理'];
            const childen = nursing_level.map!((val: any) => {
                return (<Option key={val} value={val}>{val}</Option>);
            });
            this.setState({ NursingLevel: childen });
            condition = { template_type: '详细能力评估' };
        } else {
            condition = { template_type: '初步能力评估' };
        }
        AppServiceUtility.assessment_template_service.get_assessment_template_list!(condition)!
            .then((data: any) => {
                if (data.result) {
                    this.setState({
                        template_list: data.result
                    });
                }
            });
        if (this.props.baseData) {
            AppServiceUtility.competence_assessment_service.get_competence_assessment_list!({ id: this.props.baseData['id'] }, 1, 1)!
                .then((data) => {
                    this.setState({
                        project_list: data!.result![0].project_list
                    });
                });
        }

    }
    formSub = (e: any) => {
        e.preventDefault();
        let { form } = this.props;
        form.validateFields((err: any, values: any) => {
            if (!err) {
                let obj: any = {}, project_list = [];
                let list = [];
                for (let key in values) {
                    if (key.indexOf('___') > 0) {
                        if (key.split('___').length > 2) {
                            list = key.split('___');
                            let radio_list = [];
                            radio_list = list[1].split(';');
                            let new_radio_list: any = [];
                            radio_list.forEach((item: any) => {
                                new_radio_list.push(JSON.parse(item));
                            });
                            let project = {
                                ass_info: {
                                    project_name: list[0],
                                    dataSource: new_radio_list,
                                    selete_type: list[2],
                                    value: values[key]
                                }
                            };
                            project_list.push(project);
                        } else {
                            let project = {
                                ass_info: {
                                    project_name: key.split('___')[0],
                                    selete_type: key.split('___')[1],
                                    value: values[key]
                                }
                            };
                            project_list.push(project);
                        }

                    } else {
                        obj[key] = values[key];
                    }
                }
                /** 评估记录 */
                let assessment_records: object = {
                    // 选择模板
                    template: values['template'],
                    // 服务项目
                    project_list: project_list,
                    // 评估得分
                    total_score: values['total_score'],
                    // 评估人
                    evaluator: values['evaluator'],
                    // 护理等级
                    nursing_level: values['nursing_level'] ? values['nursing_level'] : '',
                    // 评估意见
                    assessment_opinions: values['assessment_opinions'],
                };
                this.props.formSubmit(err, assessment_records);
            }
        });

    }
    // 计算得分
    // 要通过value，遍历dataSource得出真正的分数
    score_calc = (id: any, e: any, type: number, dataSource: any) => {
        let score_array = this.state.score_array;
        let serial_number;
        if (type === 1) {
            // 单选
            serial_number = [e.target.value || 0];
        } else if (type === 2) {
            // 多选
            serial_number = e || [];
        } else if (type === 4) {
            // 下拉
            serial_number = [e || 0];
        }
        let relation: any[] = [];
        dataSource.map((item: any) => {
            relation['ny' + item['serial_number']] = item['score'];
        });
        // 这是得出真正的分数
        let now_score = serial_number.map((item: any) => {
            return relation['ny' + item];
        });
        // 储存在中转变量的都是真正的分数
        score_array[id] = now_score;
        let score = 0;
        for (let i in score_array) {
            if (score_array[i]) {
                for (let j in score_array[i]) {
                    if (score_array[i][j]) {
                        score += parseInt(score_array[i][j], 0);
                    }
                }
            }
        }
        // score = score! + parseInt(e.target.value, undefined);
        this.setState({
            score,
            score_array,
        });
    }
    render() {
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 2 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 22 },
            },
        };
        const { getFieldDecorator } = this.props.form!;
        let { baseData } = this.props;
        let { isTplchange } = this.state;
        let template = this.state.template_list!.map((key, value) => {
            return <Select.Option key={key.id}>{key.template_name}</Select.Option>;
        });

        // 初步评估
        // 初始化，抑制报错
        if (!baseData) {
            baseData = {};
        }
        // 模板
        baseData!['template'] = baseData!['template'] || "";
        // 模板选项
        baseData!['project_list'] = isTplchange ? this.state.project_list : (baseData!['project_list'] || this.state.project_list);
        // 评估得分
        baseData!['total_score'] = isTplchange ? this.state.score : (baseData!['total_score'] || this.state.score);
        // 评估人
        baseData!['evaluator'] = baseData!['evaluator'] || CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER) && CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER).name ? CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER).name : '';
        // 评估意见
        baseData!['assessment_opinions'] = baseData!['assessment_opinions'] || "";
        let project: any = baseData!['project_list']!.map((item: any, index: number) => {
            if (item.hasOwnProperty("ass_info")) {
                if (item.ass_info.hasOwnProperty("selete_type")) {
                    if (item.ass_info.selete_type === "1") {
                        let radio_list = '';
                        let item_content: any;
                        if (item.ass_info.hasOwnProperty("dataSource")) {
                            item.ass_info.dataSource.forEach((item: any) => {
                                radio_list = radio_list + JSON.stringify(item) + ";";
                            });
                            radio_list = radio_list.slice(0, radio_list.length - 1);
                            console.log(radio_list, "a-----------------------------------");
                            item_content = (
                                <Form.Item label={item.ass_info.project_name}>
                                    {getFieldDecorator(item.ass_info.project_name + "___" + radio_list + "___1", {
                                        initialValue: item.ass_info.value ? item.ass_info.value : '',
                                        rules: [{
                                            required: true,
                                            message: '请选择' + item.ass_info.project_name,
                                        }],
                                    })(
                                        <Radio.Group onChange={(e: any) => this.score_calc(item.ass_info.id, e, 1, item.ass_info.dataSource)}>
                                            {item.ass_info.dataSource!.map((i: any, idx: any) => {
                                                return <Radio value={i.serial_number} key={idx}>{i.option_content}</Radio>;
                                            })}
                                        </Radio.Group>
                                    )}
                                </Form.Item>
                            );
                        }
                        return item_content;
                    } else if (item.ass_info.selete_type === "2") {
                        let radio_list = '';
                        let item_content: any;
                        if (item.ass_info.hasOwnProperty("dataSource")) {
                            item.ass_info.dataSource.forEach((item: any) => {
                                radio_list = radio_list + JSON.stringify(item) + ";";
                            });
                            radio_list = radio_list.slice(0, radio_list.length - 1);
                            item_content = (
                                <Form.Item label={item.ass_info.project_name} >
                                    {getFieldDecorator(item.ass_info.project_name + '___' + radio_list + '___2', {
                                        initialValue: item.ass_info.value ? item.ass_info.value : '',
                                        rules: [{
                                            required: true,
                                            message: '请选择' + item.ass_info.project_name,
                                        }],
                                    })(
                                        <Checkbox.Group onChange={(e: any) => this.score_calc(item.ass_info.id, e, 2, item.ass_info.dataSource)}>
                                            {item.ass_info.dataSource!.map((i: any, idx: any) => {
                                                return <Checkbox key={idx} value={i.serial_number}>{i.option_content}</Checkbox>;
                                            })}
                                        </Checkbox.Group>
                                    )}
                                </Form.Item>
                            );
                        }
                        return item_content;
                    } else if (item.ass_info.selete_type === "3") {
                        const item_content = (
                            <Form.Item label={item.ass_info.project_name}>
                                {getFieldDecorator(item.ass_info.project_name + '___3', {
                                    initialValue: item.ass_info.value ? item.ass_info.value : '',
                                    rules: [{
                                        required: true,
                                        message: '请输入' + item.ass_info.project_name,
                                    }],
                                })(
                                    <Input value={this.state.project} />
                                )}
                            </Form.Item>
                        );
                        return item_content;
                    } else if (item.ass_info.selete_type === "4") {
                        let radio_list = '';
                        let item_content: any;
                        if (item.ass_info.hasOwnProperty("dataSource")) {
                            item.ass_info.dataSource.forEach((item: any) => {
                                radio_list = radio_list + JSON.stringify(item) + ";";
                            });
                            radio_list = radio_list.slice(0, radio_list.length - 1);
                            item_content = (
                                <Form.Item label={item.ass_info.project_name}>
                                    {getFieldDecorator(item.ass_info.project_name + '___' + radio_list + '___4', {
                                        initialValue: item.ass_info.value ? item.ass_info.value : '',
                                        rules: [{
                                            required: true,
                                            message: '请选择' + item.ass_info.project_name,
                                        }],
                                    })(
                                        <Select defaultValue={item.ass_info.dataSource[0].name} style={{ width: 120 }} onChange={(e: any) => this.score_calc(item.ass_info.id, e, 4, item.ass_info.dataSource)}>
                                            {item.ass_info.dataSource!.map((i: any, idx: any) => {
                                                return <Option key={idx} value={i.serial_number}>{i.option_content}</Option>;
                                            })}
                                        </Select>
                                    )}
                                </Form.Item>
                            );
                        }
                        return item_content;
                    } else if (item.ass_info.selete_type === "5") {
                        const item_content = (
                            <Form.Item label={item.ass_info.project_name}>
                                {getFieldDecorator(item.ass_info.project_name + '___5', {
                                    initialValue: item.ass_info.value ? item.ass_info.value : '',
                                    rules: [{
                                        required: true,
                                        message: '请输入' + item.ass_info.project_name,
                                    }],
                                })(
                                    <TextArea
                                        placeholder="请输入"
                                        autosize={{ minRows: 3, maxRows: 5 }}
                                    />
                                )}
                            </Form.Item>
                        );
                        return item_content;
                    } else if (item.ass_info.selete_type === "6") {
                        const item_content = (
                            <Form.Item label={item.ass_info.project_name} >
                                {getFieldDecorator(item.ass_info.project_name + '___6', {
                                    initialValue: item.ass_info.value ? item.ass_info.value : '',
                                    rules: [{
                                        required: false,
                                    }],
                                })(
                                    <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} />
                                )}
                            </Form.Item>
                        );
                        return item_content;
                    } else if (item.ass_info.selete_type === "7") {
                        const item_content = (
                            <Form.Item label={item.ass_info.project_name}>
                                {getFieldDecorator(item.ass_info.project_name + '___7', {
                                    initialValue: item.ass_info.value ? item.ass_info.value : '',
                                    rules: [{
                                        required: false,
                                    }],
                                })(
                                    <FileUploadBtn contents={"button"} action={remote.upload_url} />
                                )}
                            </Form.Item>
                        );
                        return item_content;
                    }
                }
            } else {
                return true;
            }
        });
        return (
            <div>
                <Form {...formItemLayout} onSubmit={this.formSub}>
                    <Form.Item label='选择模板'>
                        {getFieldDecorator('template', {
                            initialValue: baseData!['template'],
                            rules: [{
                                required: true,
                                message: '请选择模板'
                            }],
                        })(
                            <Select placeholder="请选择模板" showSearch={true} onChange={this.template_change}>
                                {template}
                            </Select>
                        )}
                    </Form.Item>
                    {project}
                    <Form.Item label='评估得分'>
                        {getFieldDecorator('total_score', {
                            initialValue: baseData!['total_score'],
                            rules: [{
                                required: false,
                                message: '得分'
                            }],
                        })(
                            <Input disabled={true} />
                        )}
                    </Form.Item>
                    {this.state.NursingLevel.length > 0 ? (<Form.Item label='护理等级'>
                        {getFieldDecorator('nursing_level', {
                            initialValue: baseData!['nursing_level'] ? baseData!['nursing_level'] : '',
                            rules: [{
                                required: true,
                                message: '请选择护理等级'
                            }],
                        })(
                            <Select>{this.state.NursingLevel}</Select>
                        )}
                    </Form.Item>) : ''}

                    <Form.Item label='评估人'>
                        {getFieldDecorator('evaluator', {
                            initialValue: baseData!['evaluator'] ? baseData!['evaluator'] : (CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER) && CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER).name ? CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER).name : '...'),
                            rules: [{
                                required: false,
                                message: '评估人'
                            }],
                        })(
                            <Input disabled={true} />
                        )}
                    </Form.Item>
                    <Form.Item label='评估意见'>
                        {getFieldDecorator('assessment_opinions', {
                            initialValue: baseData!['assessment_opinions'],
                            rules: [{
                                required: false,
                                message: '评估意见'
                            }],
                        })(
                            <TextArea />
                        )}
                    </Form.Item>
                </Form>
                <Row type="flex" justify='center'>
                    <Button onClick={this.props.lastStep}>
                        上一步
                    </Button>
                    <Button onClick={this.formSub}>
                        下一步
                    </Button>
                </Row>
            </div>
        );
    }
}

/**
 * 控件：初步评估表单控制器
 * 初步评估表单
 */
@addon('PreliminaryAssessmentForm', '初步评估表单', '初步评估表单')
@reactControl(Form.create<any>()(PreliminaryAssessmentForm))
export class PreliminaryAssessmentFormControl extends BaseReactElementControl {
    /** 表单提交 */
    formSubmit?: any;
    /** 上一步 */
    lastStep?: any;
    /** 基础数据 */
    baseData?: {};

}
export default Form.create<any>()(PreliminaryAssessmentForm);